'use client';
// https://sdk.vercel.ai/docs/getting-started/nextjs-app-router
import { useChat } from 'ai/react';
import { KeyboardEventHandler, useLayoutEffect, useRef } from 'react';
import { Form, Input } from 'antd';
import React from 'react';
import Markdown from '@/components/markdown';
const { TextArea } = Input;
// #----------- 上: ts类型定义 ----------- 分割线 ----------- 下: JS代码 -----------

export default function Chat() {
	const { messages, input, isLoading, handleInputChange, handleSubmit } = useChat({ api: '/chat/message' });

	const handleKeyPress: KeyboardEventHandler<HTMLFormElement> = (e) => {
		if (e.key === 'Enter') {
			e.preventDefault();
			handleSubmit(e);
		}
	};

	const scrollContainerRef = useRef<HTMLDivElement | null>(null);

	useLayoutEffect(() => {
		if (scrollContainerRef.current) {
			scrollContainerRef.current.scrollTop = scrollContainerRef.current.scrollHeight;
		}
	});

	return (
		<div className="py-6">
			<div ref={scrollContainerRef} style={{ height: 'calc(100vh - 300px)', overflow: 'auto', scrollbarWidth: 'none' }}>
				{messages.map((m) => (
					<div key={m.id} className={`flex ${m.role === 'user' ? 'flex-row-reverse' : 'justify-start'} mb-3 text-lg`}>
						<div className="ml-2">{m.role === 'user' ? 'User' : 'AI'}</div>
						<div
							style={{ whiteSpace: 'pre-line' }}
							className={`flex-1 p-4 mx-8 rounded-lg ${m.role === 'user' ? 'bg-indigo-300' : 'bg-cyan-300'}`}>
							<Markdown>{m.content}</Markdown>
							<div>{isLoading && m.role !== 'user' ? '中断回复' : ''}</div>
						</div>
					</div>
				))}
			</div>

			<Form onKeyUp={handleKeyPress} autoComplete="off">
				<TextArea
					className="w-full"
					style={{ width: '80%' }}
					rows={4}
					value={input}
					placeholder="Say something..."
					onChange={handleInputChange}></TextArea>
			</Form>
		</div>
	);
}
